//
//  ZDEmojiPackage.m
//  ZDEmojiKeyBoard
//
//  Created by Apple on 15/11/5.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDEmojiPackage.h"
#import "ZDEmoji.h"

static NSMutableArray *packages = nil;

@implementation ZDEmojiPackage


+ (instancetype)emojiPackage:(NSString *)id
{
    ZDEmojiPackage *package = [[ZDEmojiPackage alloc] init];
    
    package.id = id;
    
    return package;
}

///加载表情包数组
+ (NSArray *)emojiPackages
{
    if (!packages)
    {
        packages = [self loadEmojiPackages];
    }
    
    return packages;
}

///加载表情包数组
+ (NSMutableArray *)loadEmojiPackages
{
    //打印发现每次呼出键盘 都会加载表情包(原因是退出微博编辑时，表情控制器释放), 表情包的资源还是比较多的，每次都加载比较好性能。———— 优化方案：第一次加载 然后缓存起来，以后直接从内存取，而不要再去磁盘加载
    NSLog(@"加载表情包");
    
    NSString *plistPath = [NSString stringWithFormat:@"%@/Emoticons.bundle/emoticons.plist", [NSBundle mainBundle].bundlePath];
    
    NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    
    NSArray *packages = plistDict[@"packages"];
    
    NSMutableArray *packageArr = [NSMutableArray array];
    
    //手动创建最近表情包，放入表情包数组中
    [packageArr addObject:[self addRecentEmojiPackage]];
    
    for (NSDictionary *dict in packages)
    {
        ZDEmojiPackage *package = [ZDEmojiPackage emojiPackage:dict[@"id"]];
        
        package.emoticons = [package emojisWithId:dict[@"id"]];
        
        //追加空模型
        [package appendEmptyEmojiWith:package.emoticons];
        
        [packageArr addObject:package];
    }
    
    return packageArr;
}


///加载表情数组
- (NSArray *)emojisWithId:(NSString *)id
{
    NSString *plistPath = [NSString stringWithFormat:@"%@/Emoticons.bundle/%@/info.plist", [NSBundle mainBundle].bundlePath, id];
    
    NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    
    self.group_name_cn = plistDict[@"group_name_cn"];
    
    NSArray *emojis = plistDict[@"emoticons"];
    
    NSMutableArray *emojiArr = [NSMutableArray array];
    
    NSInteger index = 0;
    
    for (NSDictionary *dict in emojis)
    {
        ZDEmoji *emoji = [ZDEmoji emojiWithDictionary:dict];
        emoji.id = id;
        
        [emojiArr addObject:emoji];
        
        index++;
        
        //当已经添加了20个表情模型时，额外再添加一个删除按钮
        if (index == 20)
        {
            [emojiArr addObject:[ZDEmoji emojiWithRemoveBtn:YES]];
            
            index = 0;
        }
    }
    
//    NSLog(@"%@----%ld", emojiArr, emojiArr.count);
    
    return emojiArr;
}

///追加空模型
- (void)appendEmptyEmojiWith:(NSArray *)emojis
{
    int count = emojis.count % 21;
    
    if (count > 0 || emojis.count == 0)
    {
        NSMutableArray *array = [NSMutableArray arrayWithArray:emojis];
        
        //追加空模型
        for (int i = count; i < 20; i++)
        {
            [array addObject:[ZDEmoji emojiWithRemoveBtn:NO]];
        }
        
        //添加删除按钮
        [array addObject:[ZDEmoji emojiWithRemoveBtn:YES]];
        
        self.emoticons = array;
    }
}

///手动创建最近表情包
+ (instancetype)addRecentEmojiPackage
{
    //创建最近表情包
    ZDEmojiPackage *package = [self emojiPackage:nil];
    
    package.group_name_cn = @"最近";
    
    //初始化表情数组
    package.emoticons = [NSArray array];
    
    //添加空模型
    [package appendEmptyEmojiWith:package.emoticons];
    
    return package;
}

///更新最近表情包
+ (void)updateRecentPackageWithEmoji:(ZDEmoji *)emoji
{
    if (!emoji)
    {
        return;
    }
    
    //点击删除按钮 直接返回
    if (emoji.removeBtn)
    {
        return;
    }
    
    //使用次数加1
    emoji.times++;
    
    //取出最近表情包
    ZDEmojiPackage *recentPackage = packages.firstObject;
    //转换为可变数组
    NSMutableArray *emojis = [NSMutableArray arrayWithArray:recentPackage.emoticons];
    
    //备份最后一个删除按钮
    ZDEmoji *removeE = emojis.lastObject;
    //删除最后一个删除按钮
    [emojis removeLastObject];
    
    //如果最近表情包中没有该模型 就添加
    if (![recentPackage.emoticons containsObject:emoji])
    {
        [emojis addObject:emoji];
    }
    
    //按照使用次数降序排序
//    [emojis sortUsingComparator:^NSComparisonResult(ZDEmoji *e1, ZDEmoji *e2){
//        
//        if (e1.times > e2.times) {
//            
//            return NSOrderedDescending;
//        }
//        
//        if (e1.times < e2.times) {
//        
//            return NSOrderedAscending;
//        }
//        
//        return NSOrderedSame;
//    }];
    
    //按照使用次数降序排序
    //创建排序器
    NSSortDescriptor *dsp = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO comparator:^NSComparisonResult(ZDEmoji *e1, ZDEmoji *e2) {
        
        if (e1.times > e2.times) {
            
            return NSOrderedDescending;
        }
        
        if (e1.times < e2.times) {
            
            return NSOrderedAscending;
        }
        
        return NSOrderedSame;
    }];
    
    //排序
    [emojis sortUsingDescriptors:@[dsp]];
    
    //有添加对应删除一个排在最后的(使用次数最少的)
    if (![recentPackage.emoticons containsObject:emoji])
    {
        [emojis removeLastObject];
    }
    
    //最后再重新添加删除按钮
    [emojis addObject:removeE];
    
    //更新
    recentPackage.emoticons = emojis;
    packages[0] = recentPackage;
    
//    NSLog(@"最近:%@", recentPackage);
//    NSLog(@"%@", packages);
}

- (NSString *)description
{
    NSArray *array = @[@"id", @"group_name_cn", @"emoticons"];
    
    return [NSString stringWithFormat:@"%@", [self dictionaryWithValuesForKeys:array]];
}

@end
